package com.lcx.util;

import com.lcx.constact.ConfigEnum;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.Map;

/**
 * Created by dell on 2018/1/12.
 */
public class JsonHandler {

    private static ClassLoader loader;

    private static Class<?> jsonClass;

    static{
        try {
            loader = URLClassLoader.newInstance(new URL[]{new URL("file:///"+new File(ConfigUtil.getProperty(ConfigEnum.JSON_PATH)).getAbsolutePath())});
            jsonClass = loader.loadClass("com.alibaba.fastjson.JSON");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T>T parseJson(String json,Class<?> clazz){
        if(jsonClass!=null){
            return (T) ReflectUtil.invokeMethod(jsonClass,null,"parseObject",new Class[]{String.class,Class.class},json,clazz);
        }
        return null;
    }

    public static Object parseArrayJson(String json,Class<?> clazz){
        try {
            return ReflectUtil.invokeMethod(jsonClass,null,"parseArray",new Class[]{String.class,Class.class},json,clazz);
        } catch (Exception e) {
        }
        return null;
    }

    public static String toJson(Object obj){
        if(jsonClass!=null){
            return (String) ReflectUtil.invokeMethod(jsonClass,null,"toJSONString",new Class[]{Object.class},obj);
        }
        return null;
    }

    public static Map<String,Object> fastJsonToMap(String json){
        Map<String,Object> param = parseJson(json,Map.class);
        if(param!=null){
            for(Map.Entry<String,Object> m:param.entrySet()){
                if(m.getValue() != null && (m.getValue() instanceof Collection || m.getValue() instanceof Map)){
                    m.setValue(toJson(m.getValue()));
                }
            }
        }
        return param;
    }

}
